<template>
  <el-row class="height100">
    <el-col class="height100">
      <el-row class="mx__20 px-20 py-20 bg-white main-height">
        <el-col class="current-content-style">
          <el-row :gutter="10">
            <el-col :span="6" :xl="4" style="min-height: 550px; border-right: 1px solid #efefef">
              <div class="px-20 py-10 bg-layer-top">
                <el-button type="success" plain @click="modalVisible2 = true">绑定新水表</el-button>
              </div>
              <div
                class="water-meter-item"
                :class="{ activeBg: activeItemId === item.waterId }"
                v-for="item in waterMeters"
                :key="item.waterId"
                @click="showMaterInfo(item.waterId)"
              >
                <el-row type="flex" justify="end" align="middle">
                  <el-col>
                    <div class="water-merterid-color">{{ item.waterNumber }}</div>
                  </el-col>
                  <el-col>
                    <el-button v-if="!item.waterState" size="mini" type="danger">{{
                      item.waterState === false ? '已解绑' : ''
                    }}</el-button>
                  </el-col>
                  <el-col>
                    <el-button
                      size="mini"
                      type="default"
                      @click="customerBindOrUnbindHandler(item.waterState, item.waterNumber)"
                      >{{ item.waterState ? '解绑水表' : '再次绑定' }}</el-button
                    >
                  </el-col>
                </el-row>
                <p>{{ item.waterInstallAddress }}</p>
              </div>
            </el-col>
            <el-col :span="18" :xl="20">
              <el-row type="flex" justify="space-between" align="middle" class="px-20 py-10 bg-layer-top">
                <div>客户基本信息</div>
                <div>
                  <el-button type="success" plain @click="showOrUploadContract">{{
                    this.waterContractPath ? '查看开户合同' : '上传合同'
                  }}</el-button>
                  <el-button type="warning" plain @click="showModify">编辑客户信息</el-button>
                </div>
              </el-row>
              <el-descriptions class="margin-top" :column="3" size="medium" border>
                <el-descriptions-item label="客户状态">{{
                  customerBaseInfo.customerState === 1 ? '正常' : '注销'
                }}</el-descriptions-item>
                <el-descriptions-item label="客户类型">{{ customerBaseInfo.customerTypeName }}</el-descriptions-item>
                <!-- <el-descriptions-item label="业务类别">{{ customerBaseInfo.billingName }}</el-descriptions-item> -->
                <el-descriptions-item label="客户名称">{{ customerBaseInfo.customerName }}</el-descriptions-item>
                <el-descriptions-item label="客户联系电话">{{ customerBaseInfo.customerPhone }}</el-descriptions-item>
                <el-descriptions-item label="客户身份证">{{ customerBaseInfo.customerIdCard }}</el-descriptions-item>
                <el-descriptions-item label="安装地址">{{
                  customerBaseInfo.customerAddress + customerBaseInfo.customerAddressInfo
                }}</el-descriptions-item>
              </el-descriptions>

              <el-row type="flex" justify="space-between" align="middle" class="px-20 py-10 bg-layer-top mt-20">
                <div>
                  水表信息： <span class="water-merterid-color">{{ waterMeterInfo.waterNumber }}</span>
                </div>
              </el-row>
              <el-descriptions class="margin-top" :column="3" size="medium" border>
                <el-descriptions-item label="开户人">{{ customerBaseInfo.customerName }}</el-descriptions-item>
                <el-descriptions-item label="水表类型">{{ waterMeterInfo.waterTypeName }}</el-descriptions-item>
                <el-descriptions-item label="计费类型">{{ waterMeterInfo.billingName }}</el-descriptions-item>
                <el-descriptions-item label="初始读数">{{ waterMeterInfo.waterInitialCount }} 度</el-descriptions-item>
                <el-descriptions-item label="最大计量">{{ waterMeterInfo.waterMaxMeter }} 度</el-descriptions-item>
                <el-descriptions-item label="安装日期">{{
                  getUserFormatDate(waterMeterInfo.waterInstallTime)
                }}</el-descriptions-item>
                <el-descriptions-item label="安装地址">{{
                  waterMeterInfo.waterInstallAddress
                    ? waterMeterInfo.waterInstallAddress + '-' + waterMeterInfo.waterInstallAddressInfo
                    : '空'
                }}</el-descriptions-item>
              </el-descriptions>

              <el-row type="flex" class="bg-layer-body mt-20">
                <el-table :data="meterOters" style="width: 100%">
                  <el-table-column prop="associatedName" label="已关联水表人员" width="180"> </el-table-column>
                  <el-table-column prop="associatedPhone" label="电话号码"> </el-table-column>
                </el-table>
              </el-row>
              <el-row class="mt-20 py-20">
                <el-col :span="24" class="text-center">
                  <el-button type="primary" class="btn-back" @click="$router.push('/home/customems')">返回</el-button>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-col>
    <el-dialog title="编辑客户信息" :visible.sync="modalVisible" width="50%">
      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="150px">
        <el-form-item label="客户状态" prop="customerState">
          <el-select v-model="editForm.customerState" placeholder="请选择客户状态">
            <el-option label="正常" :value="1"></el-option>
            <el-option label="注销" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户手机" prop="customerPhone">
          <el-input v-model="editForm.customerPhone" style="width: 220px"></el-input>
        </el-form-item>
        <el-form-item label="客户地址" prop="customerAddress">
          <el-cascader
            style="width: 220px"
            ref="cascader"
            v-model="checkedAddessValues"
            :options="data"
            :props="addressProps"
            clearable
            size="mini"
            separator="-"
            placeholder="请选择"
            :show-all-levels="true"
            @expand-change="handleCheck"
            @change="handleChange"
          ></el-cascader>
          <span class="px-20">{{ editForm.customerAddress }}</span>
        </el-form-item>
        <el-form-item label="详细地址" prop="customerPhone">
          <el-input v-model="editForm.customerAddressInfo" style="width: 220px"></el-input>
        </el-form-item>
        <el-form-item label="客户类别" prop="customerTypeId">
          <el-select v-model="editForm.customerTypeId" placeholder="请选择客户类型">
            <el-option
              v-for="item in optionsCustomerTypes"
              :key="item.customerTypeId"
              :label="item.customerTypeName"
              :value="item.customerTypeId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="变更原因" prop="changeInfo">
          <el-input type="textarea" v-model="editForm.changeInfo"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="modalVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateCustomerInfoFn('editForm')">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="绑定新水表" :visible.sync="modalVisible2" width="30%">
      <el-form :model="newForm" :rules="newFormRules" ref="newForm" label-width="100px">
        <el-form-item label="水表编号" prop="waterMeterId">
          <el-input v-model="newForm.waterMeterId"></el-input>
          <div class="sub-title">如需添加多个水表，请用逗号隔开</div>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="modalVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="bindNewWaterMeterHandler('newForm')">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="上传水表开户合同" :visible.sync="modalUploadVisible" width="40%">
      <el-form label-width="100px">
        <el-form-item label="水表编号">
          <el-input v-model="waterMeterInfo.waterNumber" readonly></el-input>
          <div class="sub-title">自动获取</div>
        </el-form-item>
        <el-form-item label="开户合同">
          <el-upload
            class="upload-demo"
            action="/"
            :file-list="fileList"
            :limit="1"
            :on-change="handleChangeFile"
            :on-remove="handleRemoveFile"
            accept="pdf"
            :auto-upload="false"
          >
            <el-button size="small" type="primary">选择上传的合同文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传.pdf文件。</div>
          </el-upload>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="modalUploadVisible = false">取 消</el-button>
        <el-button type="primary" @click="uploadContractPdfHandler">确 定</el-button>
      </span>
    </el-dialog>
  </el-row>
</template>

<script>
import {
  getCustomerInfo,
  updateCustomerInfo,
  getCustomerType,
  customerBindOrUnbind,
  queryRootRegionAll,
  queryChildrenRegionAll,
  getUnBindingWaterMeterDetailInfo,
  uploadCustomeForWaterMeterContract
} from './../config/api'
import { getUserFormatDate } from './../utils/dateUtils.js'

export default {
  watch: {
    checkedAddessValues(val) {
      console.log('checkedAddessValues', val)
      this.checkedKeys = val
      // 获取到选择的节点数组对象
      let arr = this.$refs.cascader.getCheckedNodes()
      // 拿到数组里面的所有三级联动的节点数组
      let pathNodes = arr[0].pathNodes

      // 获取中文地名
      let add = []
      pathNodes.forEach(el => {
        add.push(el.label)
      })
      // console.log(add)
      // 赋值中文地名给属性变量
      this.editForm.customerAddress = add.join('-')
    },
    level_1(val) {
      // console.log(val)
      let regionArr = []
      let idArr = []
      val.forEach(el => {
        // 这个对象的属性，和defaultProps的配置有关联，label对应的值，要是这个对象里面的地名的属性
        // level属性，用来判断是几级地域
        let obj = { id: el.regionId, regionName: el.regionName, level: 1 }
        regionArr.push(obj)
        idArr.push(el.regionId)
      })
      this.data = regionArr
      this.defaultExpandedKeys = idArr
    }
  },
  data() {
    return {
      uploadFile: {}, //上传的合同
      fileList: [], // 上传的文件列表
      activeItemId: 0, // 当前激活的水表
      waterContractPath: '', //水表对应的合同
      waterMeters: [], //所有绑定或未绑定的水表和客户信息 ,数组
      customerBaseInfo: {}, // 客户基本信息
      waterMeterInfo: [], // 水表信息
      meterOters: [], //关联人员
      modalUploadVisible: false, // 合同上传模态框
      modalVisible: false, //模态框显示、隐藏
      modalVisible2: false, // 添加新水表的modal变量
      // 添加新水表
      newForm: {
        waterMeterId: ''
      },
      // 添加新水表 rules
      newFormRules: {
        waterMeterId: [
          { required: true, message: '请输入水表编号', trigger: 'blur' }
          // { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 编辑客户信息
      editForm: {
        customerId: '',
        customerState: 0,
        customerPhone: '',
        customerAddress: '',
        customerAddressInfo: '',
        changeInfo: '', // 改变原因
        customerTypeId: 1
      },
      // 编辑客户信息 rules
      editRules: {
        customerPhone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { min: 11, max: 11, message: '长度11 个字符', trigger: 'blur' }
        ],
        customerAddress: [{ required: true, message: '请输入客户地址', trigger: 'blur' }],
        changeInfo: [{ required: true, message: '请输入改变原因', trigger: 'blur' }],
        customerTypeId: [{ required: true, message: '请选择客户类型', trigger: 'change' }],
        customerState: [{ required: true, message: '请选择客户状态', trigger: 'change' }]
      },
      tableData: [],
      optionsCustomerTypes: [], // 客户类型
      // 三级联动的props配置
      addressProps: {
        expandTrigger: 'click',
        value: 'id', // 多级选择器的option项的value对应数据中的id属性
        label: 'regionName', // 多级选择器的option项的label对应数据中的regionName属性
        lazy: true,
        lazyLoad: this.loadNode
      },
      level_1: [], //存储请求回来的1级地域
      checkedKeys: [], // 选择的地域id
      data: [], //root 地域数组
      checkedAddessValues: [] // 选择的地域名称
    }
  },
  // components: { PageTitle },
  created() {
    // console.log(this.$route)
    this.getCustomerInfosFn()
    this.queryRootRegionAllHandler()
  },
  methods: {
    // 调用上传合同文件的接口
    uploadContractPdfHandler() {
      if (!this.waterMeterInfo?.waterNumber) {
        this.$alert('没有绑定水表，不能上传开户合同')
        return
      }
      if (!this.uploadFile) {
        this.$alert({ message: '请选择文件' })
        return
      }
      let f = new FormData()
      f.append('file', this.uploadFile)
      uploadCustomeForWaterMeterContract({ waterNumber: this.waterMeterInfo.waterNumber }, f).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '上传成功',
            type: 'success'
          })
          this.modalUploadVisible = false
          this.uploadFile = null
          this.fileList = []
          // console.log(res)// 没有返回文件路径，只能重新调用接口
          this.getCustomerInfosFn()
        } else {
          this.$message({
            message: '上传失败',
            type: 'error'
          })
        }
      })
    },
    // 删除文件
    handleRemoveFile() {
      this.uploadFile = null
    },
    // 选择上传的合同文件
    handleChangeFile(file) {
      // console.log(file)
      this.uploadFile = file?.raw
      // console.log(fileList)
      if (file?.raw.type !== 'application/pdf') {
        this.$alert('只能上传pdf文件')
        this.uploadFile = null
        this.fileList = []
      }
      // console.log(this.uploadFile)
    },
    //开户合同查看或上传
    showOrUploadContract() {
      if (this.waterContractPath) {
        let a = document.createElement('a')
        a.href = this.imgUrl + this.waterContractPath
        a.target = '_blank'
        document.body.appendChild(a)
        a.click()
        a.remove()
      } else {
        // console.log('显示上传界面')
        this.modalUploadVisible = true
      }
    },
    // 获取一个节点的子级
    getChildReginHandler(id) {
      return queryChildrenRegionAll({ regionParentId: id }).then(res => {
        // console.log(res)
        if (res.code === 200) {
          return res.data
        }
      })
    },
    // 动态加载子tree
    loadNode(node, resolve) {
      // console.log(node)
      if (node.root) return
      this.getChildReginHandler(node.data.id).then(res => {
        console.log(res)
        let level = node.data.level + 1
        let regionArr = []
        let leaf = false
        level === 3 && (leaf = true)
        res.forEach(el => {
          let obj = { id: el.regionId, regionName: el.regionName, level, leaf }
          regionArr.push(obj)
        })
        console.log(regionArr)
        resolve(regionArr)
      })
    },
    // 选择1、2级别的地域时触发
    handleCheck(vlue) {
      console.log(vlue) // [6,7]
    },
    // 选中或清除选择的地域时触发的事件函数
    handleChange(value) {
      console.log(value) // 返回：[1,2,14]
    },
    // 查询所有根地域
    queryRootRegionAllHandler() {
      queryRootRegionAll().then(res => {
        if (res.code === 200) {
          // console.log(res)
          this.level_1 = res.data
        } else {
          this.$message({
            message: '查询根地域失败',
            type: 'error'
          })
        }
      })
    },
    getUserFormatDate,
    // 为客户绑定新水表
    bindNewWaterMeterHandler(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let customerId = this.customerBaseInfo.customerId
          let state = true
          let waterNumberArr = [...this.newForm.waterMeterId.split(',')]
          console.log('waterNumberArr', waterNumberArr) // ['500123',...]
          // 接口再修改需求，--需要先判断水表有没有安装时间，才能绑定水表--
          getUnBindingWaterMeterDetailInfo({ waterNumber: waterNumberArr }).then(res => {
            console.log('未绑定的水表信息：', res)
            let waterMeterList = res.data
            let targetArr = [] // 存没有安装地址的水表的编号
            waterMeterList.forEach(el => {
              if (!el.waterInstallTime && !el.waterInstallAddress) {
                targetArr.push(el.waterNumber)
              }
            })

            if (res.code === 200 && targetArr.length == 0) {
              // 发起绑定水表
              customerBindOrUnbind({ customerId, state, waterNumberArr }).then(res => {
                if (res.code === 200) {
                  this.modalVisible2 = false
                  this.getCustomerInfosFn()
                  this.$message({
                    message: '绑定新水表成功',
                    type: 'success'
                  })
                }
              })
            } else {
              this.$confirm(targetArr, '以下水表没有安装信息')
                .then(() => {
                  // 默认选择第一个给做跳页面的参数
                  this.$router.push('/home/waterquality_detail?waterNumber=' + targetArr[0])
                })
                .catch(() => {
                  this.$message({
                    message: '请先去完善水表的安装信息后才可以绑定到客户。'
                  })
                })
            }
          })
        }
      })
    },
    // 绑定或解绑水表
    customerBindOrUnbindHandler(state, id) {
      // console.log(state, id)
      let customerId = this.customerBaseInfo.customerId

      customerBindOrUnbind({ customerId, state: !state, waterNumberArr: [id] }).then(res => {
        if (res.code === 200) {
          console.log('res:::', res)
          this.getCustomerInfosFn()
          this.$message({
            message: res.msg,
            type: 'success'
          })
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      })
    },
    // 切换水表信息
    showMaterInfo(id) {
      let arr = this.waterMeters
      for (let i = 0; i < arr.length; i++) {
        if (id === arr[i].waterId) {
          this.waterMeterInfo = arr[i]
          this.meterOters = arr[i].associatedList
          this.activeItemId = arr[i].waterId
          this.waterContractPath = arr[i].waterContractPath
          console.log('切换水表：', this.waterContractPath)
        }
      }
    },
    // 获取客户信息
    getCustomerInfosFn() {
      getCustomerInfo({ customerId: this.$route.query.id }).then(async res => {
        if (res.code === 200) {
          // console.log(res.data)
          this.waterMeters = []
          this.customerBaseInfo = { ...res.data.customer, ...res.data.customerType }
          await res.data.waterMeterDtoList.forEach(el => {
            // console.log(el)
            let obj = {
              ...el.waterMeter,
              ...el.billingBasePrice,
              ...el.waterType,
              associatedList: el.associatedList
            }
            this.waterMeters.push(obj)
          })
          // console.log(this.waterMeters)
          if (this.waterMeters.length > 0) {
            // 默认显示第一个水表的信息
            this.waterMeterInfo = {
              ...this.waterMeters[0]
            }
            this.meterOters = this.waterMeters[0].associatedList
            this.activeItemId = this.waterMeters[0].waterId
            this.waterContractPath = this.waterMeters[0].waterContractPath
          }
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
        }
      })
    },
    // 显示编辑客户信息模态框
    showModify() {
      this.editForm = { ...this.editForm, ...this.customerBaseInfo }
      this.modalVisible = true
      getCustomerType().then(res => {
        if (res.code === 200) {
          this.optionsCustomerTypes = res.data
        }
      })
    },
    // 更新客户信息
    updateCustomerInfoFn(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let params = {
            // address: this.editForm.customerAddress,
            address: this.checkedKeys[this.checkedKeys.length - 1], //【1，2，14】z最后一个ID
            addressInfo: this.editForm.customerAddressInfo,
            phone: this.editForm.customerPhone,
            changeInfo: this.editForm.changeInfo,
            state: this.editForm.customerState,
            customerId: this.editForm.customerId,
            customerTypeId: this.editForm.customerTypeId
          }
          updateCustomerInfo(params).then(res => {
            console.log(res)
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: res.msg
              })
              this.modalVisible = false
              this.getCustomerInfosFn()
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        }
      })
    }
  }
}
</script>

<style>
.water-merterid-color {
  color: rgb(56, 54, 54);
}
.sub-title {
  color: green;
}
.activeBg {
  background-color: #1dc9b7;
  color: white;
}
.activeBg .water-merterid-color {
  color: #fff;
}
.water-meter-item:hover {
  background-color: #886ab5;
  transition: all 0.3s;
}
.water-meter-item:hover .water-merterid-color {
  color: #000;
}
.water-meter-item:hover > p {
  color: #000;
}
.water-meter-item {
  border: 1px solid rgb(199, 197, 197);
  border-radius: 3px;
  margin: 10px 0;
  padding: 10px;
  cursor: pointer;
}
.water-meter-item > p {
  color: rgb(94, 93, 93);
  font-size: 14px;
}
.bg-layer-top {
  background-color: #f1f9fd !important;
}
.bg-layer-body {
  background-color: rgb(224, 215, 215);
  border: 1px solid rgb(208, 202, 209);
}
.kf-label {
  display: inline-block;
  line-height: 40px;
  /* width: 120px;
  text-align: right; */
  margin-right: 10px;
  color: grey;
}
.table-header {
  background-color: rgb(100, 67, 100);
}
</style>
